import time

import pygame
import threading
import datetime


class JoystickController:
    def __init__(self):
        pygame.init()
        pygame.joystick.init()
        self.joystick_pos = [200, 200]
        self.pre_pos = [200, 200]
        self.joystick = None
        self.joystick_data = []
        if pygame.joystick.get_count() > 0:
            self.joystick = pygame.joystick.Joystick(0)
            self.joystick.init()
            # self.last_move_time = time.time()
            print(f"检测到 joystick：{self.joystick.get_name()}")
        else:
            print("没有找到 joystick")
        self.running = False

        # self.is_moving = False
        # self.move_timeout = 1  # 运动超时时间（秒）：停止移动后，超过此时长才判定为静止

    def start(self):
        if not self.joystick:
            print("无法启动，无 joystick 连接")
            return

        self.running = True
        while self.running:
            # 根据超时机制更新运动状态
            # current_time = time.time()
            # # 如果距离最后一次运动的时间 < 超时时间，则视为仍在运动
            # self.is_moving = (current_time - self.last_move_time) < self.move_timeout
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.JOYAXISMOTION:
                    x_axis = self.joystick.get_axis(1)
                    y_axis = self.joystick.get_axis(0)

                    # =====add 20250427======
                    # self.joystick_pos = [200+x_axis*200, 200-y_axis*200]
                    self.joystick_pos = [200 + x_axis * 0, 200 - y_axis * 100]
                    # print(self.joystick_pos)
                    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]  # 毫秒级时间戳

                    # 添加数据到列表中
                    self.joystick_data.append([timestamp, self.joystick_pos[0], self.joystick_pos[1]])
                    # self.last_move_time = time.time()

                    # =====end add======

                elif event.type == pygame.JOYBUTTONDOWN:
                    print(f"Button {event.button} pressed")

                elif event.type == pygame.JOYBUTTONUP:
                    print(f"Button {event.button} released")

            # print( self.is_moving)

    def stop(self):
        self.running = False
        if self.joystick:
            self.joystick.quit()
        pygame.quit()

    def run_in_thread(self):
        thread = threading.Thread(target=self.start)
        thread.start()


if __name__ == "__main__":
    joystick = JoystickController()
    joystick.run_in_thread()  # 在后台启动 joystick 数据采集
    try:
        while True:
            pass
    finally:
        joystick.stop()
